package com.zcsy.manage.web.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestContext;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.system.Button;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.service.system.IButtonService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IRoleService;

/**  
 * @Project: manage
 * @Title: RoleButtonController.java
 * @Package com.zcsy.shop.web.system
 * @Description: TODO
 *
 * @author xiangjw 303310059@qq.com
 * @date 2015年8月13日 上午5:34:00
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @version V1.0  
 */
@Controller
@RequestMapping(value = "/button")
public class RoleButtonController {
    
    private static final int BUTTON_ID = 0; //初始化新增id
    private static final int BUTTON_ADD = 1; //跳转新增按钮页面type为1
    private static final int BUTTON_EDIT = 2; //跳转新增按钮页面type为2
	
	@Autowired
	private IButtonService buttonService;
	
	@Autowired
    private IMenuService menuService;
	
	@Autowired
    private IRoleService roleService;

	@Autowired
	private IDictService dictService;
	
	@RequestMapping(value="queryAllBtns" , method = RequestMethod.GET)
	public String queryAllBtns(Model model,@QueryParam("roleId") String roleId,@Context HttpServletRequest req){
	    
	    List<Button> buttonList = buttonService.queryRoleButton(roleId);
	    List<String> menus = new ArrayList<String>();
	    Role role = roleService.getRole(roleId);
	    
        for (Button btn : buttonList) {
            if (btn.getMenuName() != null) {
                String name = btn.getMenuName();
                menus.add(name);
            }
        }
        
        //去重
        HashSet h  =   new  HashSet(menus);
        menus.clear();
        menus.addAll(h);
	    
	    model.addAttribute("btns",buttonList);
	    model.addAttribute("menus",menus);
	    model.addAttribute("role",role);
	    
		return "system/role/roleButton";
	}  
	
	
	@RequestMapping(value="getBtnCache" , method = RequestMethod.GET)
	public List<Button> getRoleButtonsFromCache(@QueryParam("roleId") String roleId,@Context HttpServletRequest req){
		return buttonService.getRoleButtonsFromCache(roleId);
	}
	
	@RequestMapping(value="updateRbtn" , method = RequestMethod.POST)
	@ResponseBody
	public RequestJson updateRoleButton(@RequestParam(value="buttons[]") String[] buttons ,String roleId,@Context HttpServletRequest req){
		RequestJson json = new RequestJson();
		
		try {
			buttonService.updateRoleButton(getButtonsFromString(buttons), roleId);
			json.setSuccess(true);
			json.setObj(RequestContext.getSession().getAttribute(RequestConstants.USER_SESSION_ID));
		} catch (Exception e) {
			e.printStackTrace();
			json.setSuccess(false);
			json.setMsg("更新失败");
		}
		
		return json;
	}
	
	private Button[] getButtonsFromString(String[] btns){
		Button[] buttons = new Button[btns.length];
		int j = Constants.STATE_DISABLED;
		try {
		    for (int i = 0 ; i < btns.length ; i++) {
		        Button btn = buttonService.selectByPrimaryKey(btns[i]);
	            buttons[j] = btn;
	            j++;
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buttons;
	}
	
	
	/**
	 * @Description 根据条件搜索按钮
	 * @param model 
	 * @param pNo   当前页
	 * @param mkey  菜单名称
	 * @param bkey  按钮名称
	 * @param req   用户的请求
	 * @return      返回的结果
	 * @author xujl 850789178@qq.com
	 * @date 2016年1月14日
	 * @see 
	 */
	@RequestMapping(value="btnList" , method = RequestMethod.GET)
	public String btnList(Model model,Integer pNo, Integer pSize, String mkey,String bkey,@Context HttpServletRequest req){

	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
		Button record = new Button();
		record.setMenuName(mkey);
		record.setName(bkey);
		
		List<Button> btns = buttonService.queryButton(record);
		PageInfo<Button> info = new PageInfo<Button>(btns);

		model.addAttribute("buttonList", info);
        model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("menuName", mkey);
        model.addAttribute("name", bkey);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "system/button/btnList";
	}
	
    /**
     * @Description 新增和编辑按钮<br>
     * 
     * @param mkey 菜单名称
     * @param bkey 按钮名称
     * @param bvalue 按钮值
     * @param id 当前记录id
     * @param memo 备注
     * @param req 用户请求
     * @return 返回结果1：成功 0： 失败
     * @author caiyinli 13277030520@qq.com
     * @date 2016年2月26日
     * @see 
     */
    @RequestMapping(value="editBtn" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdate(String mkey,String bkey,String bvalue,String id,String memo,HttpServletRequest req){
        RequestJson result = new RequestJson();
        Button btn = new Button();
        btn.setMenuName(mkey);
        btn.setName(bkey);
        btn.setValue(bvalue);
        btn.setMemo(memo);
        
        try {
            if(Integer.valueOf(id) != BUTTON_ID){
            	btn.setId(id);
            	buttonService.updateByPrimaryKey(btn);
            }else{
            	btn.setId(UniqueNumberUtils.get18UniqueNumber());
            	buttonService.insert(btn);
            }
            result.setSuccess(true);
        } catch (Exception e) {
        	e.printStackTrace();
            result.setMsg("操作失败");
        }
        return result;
    }
	
    /**
     * @Description 批量删除按钮<br>
     * 
     * @param ids 删除按钮id的集合
     * @param req 用户请求
     * @return 1：删除成功 0：删除失败
     * @author caiyinli 13277030520@qq.com
     * @date 2016年2月26日
     * @see 
     */
    @RequestMapping(value="deleteByIds" , method = RequestMethod.GET)
    @ResponseBody
    public RequestJson deleteByIds(@RequestParam(value="ids[]") final String[] ids,@Context HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
        	for(String item : ids){
        		int count = buttonService.checkIfButtonUsed(item);
        		if(count > 0){
    				result.setMsg("已经有角色使用了某个按钮，无法删除");
                    result.setSuccess(false);
                    return result;
    			}
        	}
        	
          int flag = buttonService.deleteByPrimaryKeys(ids);
          if(flag==Constants.SQL_RESULT_ERROR){
              result.setMsg("删除失败");
              result.setSuccess(false);
          }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("删除失败");
            result.setSuccess(false);
        }
        return result;
    }
    
    
    

    /**
     * @Description 跳转新增或编辑页面<br>
     * 
     * @param model
     * @param id 新增：id为0 编辑：id为当前记录id
     * @return  返回新增或编辑页面
     * @author caiyinli 13277030520@qq.com
     * @date 2016年2月26日
     * @see 
     */
    @RequestMapping(value = "buttonBox", method = RequestMethod.GET)
    public String selectByPrimaryKey(Model model,@QueryParam("id") String id) {
        
    	try {
    		if(String.valueOf(BUTTON_ID) == id){
                model.addAttribute("type", BUTTON_ADD);
                model.addAttribute("button", null);
    		}else{
    			Button list = buttonService.selectByPrimaryKey(id);
    			model.addAttribute("button",list);
    			model.addAttribute("type", BUTTON_EDIT);
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return "system/button/btnEdit";
    }
    
    
    
    
    
}
